﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GMusicBox.Core;

namespace GMusicBox
{
    public partial class frmSearch : Form
    {
        public frmSearch(frmMain fm)
        {
            InitializeComponent();

            for (int i = 0; i < 10; i++)
            {
                Label l = new Label();
                l.AutoSize = false;
                l.BackColor = Color.White;
                l.Location = new Point(23 * i, 0);
                l.Size = new Size(23, 23);
                l.Text = "";
                l.TextAlign = ContentAlignment.MiddleCenter;

                l.MouseEnter += delegate(object sender, EventArgs e)
                {
                    if (((Control)sender).Tag != null)
                        ((Control)sender).BackColor = Color.FromArgb(235, 235, 235);
                };

                l.MouseLeave += delegate(object sender, EventArgs e)
                {
                    if (((Control)sender).Tag != null)
                        ((Control)sender).BackColor = currentPage == (int)((Control)sender).Tag ? Color.FromArgb(235, 235, 235) : Color.White; ;
                };

                l.Click += delegate(object sender, EventArgs e)
                {
                    if (((Control)sender).Tag != null)
                    {
                        currentPage = (int)((Control)sender).Tag;
                        clickedIndex = panel1.Controls.IndexOf((Control)sender);
                        panel1.Enabled = false;
                        label2.Visible = true;
                        bgw.RunWorkerAsync();
                    }
                };
                panel1.Controls.Add(l);
            }

            btnAddTo.Text = "添加到";
            btnDownload.Text = "下载";
            btnTryListen.Text = "试听选中歌曲";

            this.fm = fm;
            this.TopMost = Core.Setting.StandardSetting.TopMost;
        }

        public frmSearch(frmMain fm, string keyWord) : this(fm)
        {
            txtKeyWord.Text = keyWord;
            btnSearch_Click(btnSearch, null);
        }

        internal Song[] ss;
        int currentPage = 0;
        int totalPages = 0;
        int clickedIndex = -1;
        frmMain fm;

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (bgw.IsBusy)
            {
                if (VTaskDialog.CanUseTankDialog())
                    VTaskDialog.ShowTaskDialog("当前正在执行另一项搜索，请等待当前搜索任务完成后再执行搜索操作。", "谷歌音乐盒", "无法执行搜索", VTaskDialog.TaskDialogButton.OK, VTaskDialog.TaskDialogIcon.Warning);
                else MessageBox.Show("当前正在执行另一项搜索，请等待当前搜索任务完成后再执行搜索操作。", "谷歌音乐盒", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (txtKeyWord.Text == "")
            {
                if (VTaskDialog.CanUseTankDialog())
                    VTaskDialog.ShowTaskDialog("请先输入搜索关键字再进行搜索。", "提示", "无法进行搜索", VTaskDialog.TaskDialogButton.OK, VTaskDialog.TaskDialogIcon.Warning);
                else MessageBox.Show("请先输入搜索关键字再进行搜索。", "无法进行搜索", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            currentPage = 0;
            this.Text = "与“" + txtKeyWord.Text + "”有关的搜索结果";
            Musics.Rows.Clear();
            label2.Text = "加载中，请稍候...";
            label2.Visible = true;
            bgw.RunWorkerAsync();
        }

        private void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = Song.Search(txtKeyWord.Text, currentPage, out totalPages);
            totalPages /= 20;
        }

        private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ss = (Song[])e.Result;

            if (ss == null)
                label2.Text = "加载时出现网络错误，请重试。";
            else
            {
                RefreshPages();
                label2.Visible = false;
                panel1.Enabled = true;
            }
        }

        private void RefreshPages()
        {
            if (totalPages == 0) totalPages = 1;
            if (totalPages < 9)
            {
                for (int i = 8; i >= 0; i--)
                {
                    if (8 - i >= totalPages)
                    {
                        panel1.Controls[i].BackColor = Color.White;
                        panel1.Controls[i].Tag = null;
                        panel1.Controls[i].Text = "";
                    }
                    else
                    {
                        panel1.Controls[i].BackColor = currentPage == totalPages + i - 9 ? Color.FromArgb(235, 235, 235) : Color.White;
                        panel1.Controls[i].Tag = totalPages + i - 9;
                        panel1.Controls[i].Text = (totalPages + i - 8).ToString();
                    }
                }
            }
            else
            {
                for (int i = currentPage > totalPages - 5 ? Math.Max(0, totalPages - 9) : Math.Max(0, currentPage - 4), j = 0; i < Math.Min(Math.Max(9, 5 + currentPage), totalPages); i++, j++)
                {
                    panel1.Controls[j].BackColor = currentPage == i || clickedIndex == j ? Color.FromArgb(235, 235, 235) : Color.White;
                    panel1.Controls[j].Tag = i;
                    panel1.Controls[j].Text = (i + 1).ToString();
                }
            }
            clickedIndex = -1;

            if (currentPage > 4 && totalPages > 10)
            {
                panel1.Controls[0].ForeColor = Color.Silver;
                panel1.Controls[1].ForeColor = Color.Gray;
            }
            else
            {
                panel1.Controls[0].ForeColor = Color.Black;
                panel1.Controls[1].ForeColor = Color.Black;
            }

            if (totalPages >= 10 && !(totalPages - 5 <= currentPage))
            {
                panel1.Controls[8].ForeColor = Color.Silver;
                panel1.Controls[7].ForeColor = Color.Gray;
            }
            else
            {
                panel1.Controls[8].ForeColor = Color.Black;
                panel1.Controls[7].ForeColor = Color.Black;
            }

            DataGridViewColumn dgc = Musics.SortedColumn;
            if (dgc != null)
            {
                dgc.SortMode = DataGridViewColumnSortMode.NotSortable;
                dgc.SortMode = DataGridViewColumnSortMode.Automatic;
            }
            Musics.Rows.Clear();
            for (int i = 0; i < ss.Length; i++)
            {
                DataGridViewRow d = new DataGridViewRow();
                d.Cells.Add(new DataGridViewCheckBoxCell());
                d.Cells.Add(new DataGridViewTextBoxCell { Value = ss[i].Name });
                d.Cells.Add(new DataGridViewTextBoxCell { Value = ss[i].Artist.ToString() });
                d.Cells.Add(new DataGridViewTextBoxCell { Value = ss[i].Album.ToString() });
                d.Cells.Add(new DataGridViewImageCell { Value = res.trylisten });
                d.Cells.Add(new DataGridViewImageCell { Value = res.addtolist });
                d.Cells.Add(new DataGridViewImageCell { Value = ss[i].CanBeDownloaded ? res.download : res.nodownload });
                d.Tag = ss[i];
                Musics.Rows.Add(d);
            }
        }

        private void Musics_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && e.RowIndex >= 0 && !Musics.Rows[e.RowIndex].Selected)
            {
                Musics.ClearSelection();
                Musics.Rows[e.RowIndex].Selected = true;
            }
            if (e.RowIndex != -1)
            {
                if (e.Button == MouseButtons.Left)
                {
                    if (e.ColumnIndex == 4 || e.ColumnIndex == 5)
                    {
                        int targetIndex = fm.selected[1];
                        if (fm.selected[0] != 0) targetIndex = 0;

                        fm.songs[0][targetIndex].Songs.Add((Song)Musics.Rows[e.RowIndex].Tag);
                        fm.SaveList(targetIndex);
                        fm.ShowMsg("成功添加1首歌曲");

                        if (fm.selected[0] == 0) fm.AddItemToMusic(fm.songs[0][targetIndex][fm.songs[0][targetIndex].Songs.Count - 1]);
                        if (e.ColumnIndex == 4) fm.SetPlaying(0, targetIndex, fm.songs[0][targetIndex].Songs.Count - 1);
                    }
                    else if (e.ColumnIndex == 6)
                        Program.AddTask(new Song[] { (Song)Musics.Rows[e.RowIndex].Tag });
                }
                else if (e.Button == MouseButtons.Right)
                {
                    DataGridViewCell dgc = Musics[e.ColumnIndex, e.RowIndex];
                    mnuSearchMusic.Visible = dgc.Value != null && e.ColumnIndex != 4;
                    if (mnuSearchMusic.Visible)
                    {
                        mnuSearchMusic.Text = "搜索“" + dgc.Value.ToString() + "”";
                        mnuSearchMusic.Tag = dgc.Value.ToString();
                    }

                    Rectangle rect = Musics.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
                    contextMenu1.Show(Musics, new Point(e.X + rect.X, e.Y + rect.Y));
                }
            }
        }

        private void Musics_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            Musics_CellMouseDown(Musics, new DataGridViewCellMouseEventArgs(5, e.RowIndex, e.X, e.Y, new MouseEventArgs(e.Button, e.Clicks, e.X, e.Y, e.Delta)));
            this.Close();
        }

        private void btnAddTo_Click(object sender, EventArgs e)
        {
            ContextMenu cm = new ContextMenu();
            for (int i = 0; i < fm.songs[0].Count; i++)
            {
                MenuItem mi = new MenuItem();
                mi.Text = fm.songs[0][i].Name;
                mi.Click += delegate(object owner, EventArgs args)
                {
                    int index = ((MenuItem)owner).Index;
                    int added = 0;
                    for (int j = 0; j < Musics.Rows.Count; j++)
                    {
                        if (Musics.Rows[j].Cells[0].Value != null && (bool)Musics.Rows[j].Cells[0].Value)
                        {
                            Song s = (Song)Musics.Rows[j].Tag;
                            Song ns = Song.Create(s.Id, s.Name, s.Artist, s.Album, s.Duration, s.CanBeDownloaded, s.HasFullLyrics, s.RingtoneUrl);
                            fm.songs[0][index].Songs.Add(ns);
                            if (fm.selected[0] == 0 && fm.selected[1] == index) fm.AddItemToMusic(fm.songs[0][index][fm.songs[0][index].Songs.Count - 1]);
                            added++;
                        }
                    }
                    fm.SaveList(index);
                    fm.ShowMsg("成功添加" + added.ToString() + "首歌曲");
                };
                cm.MenuItems.Add(mi);
            }
            cm.Show(btnAddTo, new Point(0, btnAddTo.Height));
        }

        private void btnTryListen_Click(object sender, EventArgs e)
        {
            int firstIndex = -1;
            int targetIndex = fm.selected[1];
            int added = 0;

            if (fm.selected[0] == 0) targetIndex = 0;
            for (int i = 0; i < Musics.Rows.Count; i++)
            {
                if (Musics.Rows[i].Cells[0].Value != null && (bool)Musics.Rows[i].Cells[0].Value)
                {
                    Song s = (Song)Musics.Rows[i].Tag;
                    Song ns = Song.Create(s.Id, s.Name, s.Artist, s.Album, s.Duration, s.CanBeDownloaded, s.HasFullLyrics, s.RingtoneUrl);
                    fm.songs[0][targetIndex].Songs.Add(ns);
                    if (fm.selected[0] == 0 && fm.selected[1] == targetIndex) fm.AddItemToMusic(fm.songs[0][targetIndex][fm.songs[0][targetIndex].Songs.Count - 1]);
                    if (firstIndex == -1) firstIndex = fm.songs[0][targetIndex].Songs.Count - 1;
                    added++;
                }
            }

            if (firstIndex != -1)
            {
                fm.SaveList(targetIndex);
                fm.SetPlaying(0, targetIndex, firstIndex);
                fm.ShowMsg("成功添加" + added.ToString() + "首歌曲");
            }
        }

        private void txtKeyWord_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSearch_Click(btnSearch, null);
            }
        }

        private void Musics_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex > 0) e.Cancel = true;
        }

        private void mnuAddToCurrntList_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < Musics.SelectedRows.Count; i++)
            {
                Musics_CellMouseDown(Musics, new DataGridViewCellMouseEventArgs(5, Musics.SelectedRows[i].Index, 0, 0, new MouseEventArgs(System.Windows.Forms.MouseButtons.Left, 1, 0, 0, 0)));
            }
        }

        private void mnuAddTo_Popup(object sender, EventArgs e)
        {
            mnuAddTo.MenuItems.Clear();
            for (int i = 0; i < fm.songs[0].Count; i++)
            {
                MenuItem mi = new MenuItem();
                mi.Text = fm.songs[0][i].Name;
                mi.Click += delegate(object owner, EventArgs args)
                {
                    int index = ((MenuItem)owner).Index;
                    int added = 0;

                    for (int j = 0; j < Musics.Rows.Count; j++)
                    {
                        if (Musics.Rows[j].Selected)
                        {
                            Song s = (Song)Musics.Rows[j].Tag;
                            Song ns = Song.Create(s.Id, s.Name, s.Artist, s.Album, s.Duration, s.CanBeDownloaded, s.HasFullLyrics, s.RingtoneUrl);
                            fm.songs[0][index].Songs.Add(ns);
                            added++;
                        }
                    }
                    fm.SaveList(index);
                    fm.ShowMsg("成功添加" + added.ToString() + "首歌曲");
                };
                mnuAddTo.MenuItems.Add(mi);
            }
        }

        private void mnuTryListen_Click(object sender, EventArgs e)
        {
            Musics_CellMouseDown(Musics, new DataGridViewCellMouseEventArgs(4, Musics.SelectedRows[0].Index, 0, 0, new MouseEventArgs(System.Windows.Forms.MouseButtons.Left, 1, 0, 0, 0)));
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            List<Song> padds = new List<Song>();
            for (int i = 0; i < Musics.Rows.Count; i++)
                if (Musics.Rows[i].Cells[0].Value != null && (bool)Musics.Rows[i].Cells[0].Value)
                    padds.Add((Song)Musics.Rows[i].Tag);

            Program.AddTask(padds.ToArray());
        }

        private void mnuDownload_Click(object sender, EventArgs e)
        {
            List<Song> padds = new List<Song>();
            for (int i = 0; i < Musics.Rows.Count; i++)
                if (Musics.Rows[i].Selected)
                    padds.Add((Song)Musics.Rows[i].Tag);

            Program.AddTask(padds.ToArray());
        }

        private void mnuRing_Click(object sender, EventArgs e)
        {
            if (Musics.SelectedRows.Count > 0)
            {
                Song s = (Song)Musics.SelectedRows[0].Tag;
                if (s.RingtoneUrl == null || s.RingtoneUrl.Trim() == "")
                {
                    if (VTaskDialog.CanUseTankDialog())
                        VTaskDialog.ShowTaskDialog("对不起，无法找到歌曲“" + s.ToString() + "”的彩铃，您可以尝试从其他网站中寻找。", "提示", "不存在彩铃", VTaskDialog.TaskDialogButton.OK, VTaskDialog.TaskDialogIcon.Warning);
                    else MessageBox.Show("对不起，无法找到歌曲“" + s.ToString() + "”的彩铃，您可以尝试从其他网站中寻找。", "不存在彩铃", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                    System.Diagnostics.Process.Start(s.RingtoneUrl);
            }
        }

        private void mnuSearchMusic_Click(object sender, EventArgs e)
        {
            txtKeyWord.Text = ((MenuItem)sender).Tag.ToString();
            btnSearch_Click(btnSearch, null);
        }

        private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < Musics.Rows.Count; i++)
            {
                Musics.Rows[i].Cells[0].Value = chkSelectAll.Checked;
            }
        }
    }
}
